package com.example.app.page;

import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.app.R;
import com.example.app.api.LoginService;
import com.example.app.api.UploadService;
import com.example.app.config.RetrofitClient;
import com.example.app.entity.UserProfile;
import com.example.app.event.SwitchTabEvent;
import com.example.app.manager.TokenManager;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private ViewPager2 viewPager;
    private TabLayout tabLayout;

    private TokenManager tokenManager;

    private RetrofitClient retrofitClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化Retrofit客户端
        retrofitClient = RetrofitClient.getInstance((Application) getApplicationContext());
        tokenManager = retrofitClient.getTokenManager();

        viewPager = findViewById(R.id.view_pager);
        tabLayout = findViewById(R.id.tab_layout);

        // 设置ViewPager
        viewPager.setAdapter(new FragmentAdapter(this));
        viewPager.setOffscreenPageLimit(4);

        getAllReservationId();

        // 绑定TabLayout
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            switch (position) {
                case 0: tab.setText("首页"); break;
                case 1: tab.setText("预约"); break;
                case 2: tab.setText("账单"); break;
                case 3: tab.setText("我的"); break;
            }
        }).attach();
    }

    private static class FragmentAdapter extends FragmentStateAdapter {
        public FragmentAdapter(FragmentActivity fa) {
            super(fa);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            switch (position) {
                case 0: return new HomeFragment();
                case 1: return new ReservationFragment();
                case 2: return new BillFragment();
                case 3: return new ProfileFragment();
            }
            return new HomeFragment();
        }

        @Override
        public int getItemCount() {
            return 4;
        }
    }


    public void getAllReservationId(){
        if (tokenManager.getToken() == null) {
            Log.e(TAG, "请先登录！");
            return;
        }

        // 获取用户服务接口实例（带Token）
        UploadService uploadService = retrofitClient.getAuthService(UploadService.class);
        Call<ResponseBody> call = uploadService.getAllReservationId(tokenManager.getUserId());

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.isSuccessful() && response.body() != null) {
                        // 解析响应数据
                        String responseData = response.body().string();

                        // 使用Gson解析JSON数组
                        Gson gson = new Gson();
                        Type type = new TypeToken<List<String>>(){}.getType();
                        List<String> plateParkIds = gson.fromJson(responseData, type);
                        System.out.println(plateParkIds);
                        String plateParkIdsJson = gson.toJson(plateParkIds);
                        tokenManager.saverReservationId(plateParkIdsJson);
                    } else {
                        // 处理HTTP错误
                        String errorBody = response.errorBody() != null ?
                                response.errorBody().string() : "未知错误";
                        Log.e(TAG, "请求失败: HTTP " + response.code() + ", 错误信息: " + errorBody);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "解析响应失败: " + e.getMessage());

                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e(TAG, "网络错误: " + t.getMessage());
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    // 接收切换页面事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSwitchTabEvent(SwitchTabEvent event) {
        viewPager.setCurrentItem(event.getTabPosition(), true);
    }
}
